<script setup lang="ts">
import { createVNode, reactive, ref } from "vue";
import { handleTree, handleTreeFormat, serchOptions, columns } from "./data.ts";
import { IMenuTableParams, ITableData, ITypeState } from "./types.ts";
import { fetchTabelData, delRow } from "@/api/common";
import { PAGE_NUMBER, PAGE_SIZE } from "@/utils/const.ts";
import { IOperHandle, ITableResPage } from "@/utils/types/table.ts";
import AddModal from "@/views/system/menu/AddModal.vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { Modal } from "ant-design-vue";
let tableParams = reactive({
  pageNum: PAGE_NUMBER,
  pageSize: PAGE_SIZE,
});
const state = reactive<ITypeState>({
  tableData: [],
  loading: false,
  total: 0,
});
const addModalRef = ref();
const getList = async (params: IMenuTableParams) => {
  state.loading = true;
  tableParams = Object.assign({}, params);
  const { data }: ITableResPage<ITableData> = await fetchTabelData<
    IMenuTableParams,
    ITableData
  >(tableParams, "/system/menu/list");
  state.loading = false;
  state.tableData = handleTreeFormat(handleTree(data));
};
getList(tableParams);
const initTableData = (parmas: IMenuTableParams) => {
  if (JSON.stringify(parmas) === "{}") {
    // 重置
    tableParams = reactive({
      pageNum: PAGE_NUMBER,
      pageSize: PAGE_SIZE,
    });
  } else {
    const pp = {
      ...parmas,
      pageNum: parmas.pageNum ? parmas.pageNum : PAGE_NUMBER,
      pageSize: parmas.pageSize ? parmas.pageSize : PAGE_SIZE,
    };
    tableParams = Object.assign(tableParams, pp);
  }
  getList(tableParams);
};
const operHandleFun: IOperHandle<ITableData | null> = {
  // 添加
  handleAdd: (row: ITableData | null, type: string) => {
    addModalRef.value.openAddModal(type, row, state.tableData);
  },
  handleDelete: (row: ITableData | null, url: string) => {
    Modal.confirm({
      title: "删除",
      icon: createVNode(ExclamationCircleOutlined),
      content: "是否确认删除该数据？",
      async onOk() {
        await delRow(`${url}/${row?.menuId}`, "delete");
        initTableData(tableParams);
      },
    });
  },
};
const operHandle = (fun: string, row: ITableData | null, type: string) => {
  operHandleFun[fun](row, type);
};
</script>

<template>
  <div class="page-index">
    <JTableSearch :searchList="serchOptions" @setTableParams="initTableData" />
    <JTableIndex
      title="菜单列表"
      :columns="columns"
      rowKey="menuId"
      :loading="state.loading"
      :listData="state.tableData"
      :total="state.total"
      :setPages="tableParams"
      @operHandle="operHandle"
      @tableChange="initTableData"
    >
      <template v-slot:table-right>
        <a-button
          type="primary"
          v-hasPermi="['system:menu:add']"
          @click="operHandle('handleAdd', null, 'add')"
        >
          + 新增
        </a-button>
      </template>
    </JTableIndex>
    <add-modal ref="addModalRef" @refresh="initTableData" />
  </div>
</template>
